<template>
  <div class="login-page">
    <h2>用户登录界面</h2>
    <input type="text" v-model="username" placeholder="用户名">
    <input type="password" v-model="password" placeholder="密码">
    <button @click="login" :disabled="loading">
      {{ loading ? '登录中...' : '登录' }}
    </button>
    <p v-if="message" :class="messageClass">{{message}}</p>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { authAPI } from '../api'

const router = useRouter()
const username = ref('')
const password = ref('')
const message = ref('')
const loading = ref(false)

const messageClass = computed(() => {
  return message.value === '登录成功' ? 'success' : 'error'
})

const login = async () => {
  if(!username.value || !password.value){
    message.value = '请填写完整'
    return
  }

  loading.value = true
  message.value = ''

  try {
    const response = await authAPI.login({
      username: username.value,
      password: password.value
    })

    if (response.success) {
      message.value = '登录成功'
      localStorage.setItem('token', response.data.token)
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('username', response.data.user.username)
      localStorage.setItem('userInfo', JSON.stringify(response.data.user))
      setTimeout(() => {
        router.push('/dashboard')
      }, 1000)
    }
  } catch (error) {
    console.error('登录失败:', error)
    message.value = error.response?.data?.message || '登录失败，请重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  max-width: 300px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  text-align: center;
}

input, button {
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  background: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.success {
  color: #4CAF50;
}

.error {
  color: #f56c6c;
}
</style>